package com.snailct.bpp.service.client.dispatcher;
import com.snailct.bpp.commons.protocol.RespResult;
import com.snailct.bpp.service.client.IServiceInvoker;
import com.snailct.bpp.service.client.factory.ServiceInvokerFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 前端中央请求处理器,用于接收action请求,并调用相应的服务处理,返回处理结果
 *
 */
@Controller
@RequestMapping("/bpp")
public class DispatcherController {
    private static final Log logger = LogFactory.getLog(DispatcherController.class);
    /**
     * 接收规定格式的json字符串,使用客户端jar去调用相应的服务,并返回json格式数据
     * @param data 接收传入规定格式的json字符器
     * @return 返回json格式数据
     */
    @RequestMapping(value="/execute")
    @ResponseBody
    public Object execute(String data){
        JSONObject respJson = new JSONObject();
        JSONObject respData = new JSONObject();
        RespResult resp;
        try{
            IServiceInvoker serviceInvoker = ServiceInvokerFactory.getServiceInvoker();
            resp = serviceInvoker.invoke(data);
            respJson.element("success",true);
            if(resp.getRtnStr().equals("OK\r\n")){
                return respJson;
            }
            JSONArray contents = JSONArray.fromObject(resp.getRtnStr());
            respData.element("datas",contents);
            respData.element("currentPage",1);
            respData.element("totalCount",20);
            respJson.element("content",respData);
            respJson.element("errorCode","");
            respJson.element("errorMsg","");
        }catch(Exception e){
            logger.error("请求服务出错!",e);
            respJson.element("success",false);
            respJson.element("errorCode","001");
            respJson.element("errorMsg","请求服务出错!");
        }
        System.out.println(respJson);
        return respJson;
    }
}
